<?php
//Khai bao namespace
namespace Upload\Controller;

//Load lớp AbstractActionController vào CONTROLLER
use Zend\Mvc\Controller\AbstractActionController;
use Zend\Mvc\Controller\Plugin\Params;
use Upload\Form\UploadForm;       // <-- Add this import

//Load lớp ViewModel vào CONTROLLER
use Zend\View\Model\ViewModel;

class UploadController extends AbstractActionController
{
    private $_unique_salt = 'unique_salt';

    public function init() {
        parent::init();
    }

    public function indexAction()
    {
        $form = new UploadForm();

        $request = $this->getRequest();

        if ($request->isPost()) {
            // stop - neu khong tim thay file upload
            if (empty($_FILES)) die(json_encode(array('result'=>false, 'msgError'=>1)));

            $data = $request->getPost()->toArray();

//             $data = array_merge_recursive(
//                                             $request->getPost()->toArray(),
//                                             $request->getFiles()->toArray()
//                                         );
//die(json_encode($data)); die;
            $verifyToken = isset($data['timestamp']) ? md5("{$this->_unique_salt}{$data['timestamp']}") : false;

            if (!isset($data['token']) || $data['token'] != $verifyToken) die(json_encode(array('result'=>false, 'msgError'=>2)));

            $fileName = $data['Filename'];

            $uploadObj = new \Zend\File\Transfer\Adapter\Http();
            $uploadObj->setDestination(FILES_PATH);

            $result = $uploadObj->receive($fileName);

            die(json_encode(array('result'=>$result, 'filename'=>$fileName)));
       }

       $view = new ViewModel(array('form'=>$form));

       return $view;
    }
}